//
//  MZMediator.swift
//  CTMediator
//
//  Created by gby on 2023/1/28.
//


/**
 
 -----block 转 闭包----
 
 typealias CallbackType = @convention(block) (Int) -> Void
 let blockPtr = UnsafeRawPointer(Unmanaged<AnyObject>.passUnretained(block as AnyObject).toOpaque())
 let callback = unsafeBitCast(blockPtr, to: CallbackType.self)
 
 */


public class MZMediator:NSObject {
    
}

//MARK:-- 远程调用
extension MZMediator {
    
    @discardableResult
    public static func performActionWithUrl(_ urlString: String,moduleName:String? = nil) -> UIViewController? {
        guard let url = URL(string: urlString) else { return nil}
        let params = url.queryDictionary
        let actionName = url.path.replacingOccurrences(of: "/", with: "")
        return performTarget(url.host, actionName: actionName,moduleName: moduleName, params: params)
    }
}
//MARK:-- 私有方法
/*
 
 */
extension MZMediator {
    @discardableResult
    @objc public static func performTarget(_ targetName:String?, actionName:String,moduleName:String? = nil,params:[String : Any]?) -> UIViewController? {
        guard let targetName = targetName else { return nil}
        // 创建target对象
        var targetClassString = ""
        if let namespace = moduleName {
            targetClassString = "\(namespace).MZTarget_\(targetName)"
        }else {
            targetClassString = "MZTarget_\(targetName)"
        }
        let cls: AnyClass? = NSClassFromString(targetClassString)
        guard let ob = cls as? NSObject.Type else {
            return nil
        }
        let targetObj = ob.init()
        // 找到action方法
        let actionString = "Action_\(actionName):"
        let actionSel = NSSelectorFromString(actionString)
        
        guard class_getInstanceMethod(type(of: targetObj), actionSel) != nil else {
            return nil
        }
        let value = targetObj.perform(actionSel, with: params).takeUnretainedValue()
        guard let vc = value as? UIViewController else {
            return nil
        }
        return vc
    }
    
    // 仅仅是发起响应
    @discardableResult
    @objc public static func OnlyPerformTarget(_ targetName:String?, actionName:String,moduleName:String? = nil,params:[String : Any]?) -> Bool {
        guard let targetName = targetName else { return false}
        // 创建target对象
        var targetClassString = ""
        if let namespace = moduleName {
            targetClassString = "\(namespace).MZTarget_\(targetName)"
        }else {
            targetClassString = "MZTarget_\(targetName)"
        }
        let cls: AnyClass? = NSClassFromString(targetClassString)
        guard let ob = cls as? NSObject.Type else {
            return false
        }
        let targetObj = ob.init()
        // 找到action方法
        let actionString = "Action_\(actionName):"
        let actionSel = NSSelectorFromString(actionString)

        guard class_getInstanceMethod(type(of: targetObj), actionSel) != nil else {
            return false
        }
        targetObj.perform(actionSel, with: params)
        return true
    }
    
}


//MARK:--获取最上层视图
extension MZMediator {
    @objc public static func pushViewController(_ viewController:UIViewController, animated:Bool) {
        currentNavigationController()?.pushViewController(viewController, animated: animated)
    }
    @objc public static func popViewController(_ animated:Bool = true) {
        currentNavigationController()?.popViewController(animated: animated)
    }
    @objc public static func popAndPushViewController(_ viewController:UIViewController, animated:Bool) {
        pushViewController(viewController, animated: animated)
        if let count = currentNavigationController()?.viewControllers.count,count > 0 {
            let mArr = currentNavigationController()!.viewControllers
            var removeArr = [UIViewController]()
            for (index, element) in mArr.enumerated() {
                if mArr.count - 2 == index {
                    removeArr.append(element)
                }
            }
            let newArry = mArr.filter { vc in
                !removeArr.contains(vc)
            }
            currentNavigationController()?.viewControllers = newArry
        }
    }
    /// 获取顶层Nav 根据window
    @objc public static func currentNavigationController() -> UINavigationController? {
        return currentViewController()?.navigationController
    }
    
    /// 获取顶层VC 根据window
    @objc public static func currentViewController() -> UIViewController? {
        var window = UIApplication.shared.keyWindow
        //是否为当前显示的window
        if window?.windowLevel != UIWindow.Level.normal{
            let windows = UIApplication.shared.windows
            for  windowTemp in windows{
                if windowTemp.windowLevel == UIWindow.Level.normal{
                    window = windowTemp
                    break
                }
            }
        }
        let vc = window?.rootViewController
        return getCurrentViewController(withCurrentVC: vc)
    }
    
    ///根据控制器获取 顶层控制器 递归
    @objc private static func getCurrentViewController(withCurrentVC VC :UIViewController?) -> UIViewController? {
        if VC == nil {
            print("🌶： 找不到顶层控制器")
            return nil
        }
        if let presentVC = VC?.presentedViewController {
            //modal出来的 控制器
            return getCurrentViewController(withCurrentVC: presentVC)
        }
        else if let splitVC = VC as? UISplitViewController {
            // UISplitViewController 的跟控制器
            if splitVC.viewControllers.count > 0 {
                return getCurrentViewController(withCurrentVC: splitVC.viewControllers.last)
            }else{
                return VC
            }
        }
        else if let tabVC = VC as? UITabBarController {
            // tabBar 的跟控制器
            if tabVC.viewControllers != nil {
                return getCurrentViewController(withCurrentVC: tabVC.selectedViewController)
            }else{
                return VC
            }
        }
        else if let naiVC = VC as? UINavigationController {
            // 控制器是 nav
            if naiVC.viewControllers.count > 0 {
                //                return getCurrentViewController(withCurrentVC: naiVC.topViewController)
                return getCurrentViewController(withCurrentVC:naiVC.visibleViewController)
            }else{
                return VC
            }
        }
        else {
            // 返回顶控制器
            return VC
        }
    }
}


//MARK:--URL获取query字典
extension URL {
    public var queryDictionary: [String: Any]? {
        guard let query = self.query else { return nil}
        
        var queryStrings = [String: String]()
        for pair in query.components(separatedBy: "&") {
            
            let key = pair.components(separatedBy: "=")[0]
            let value = pair
                .components(separatedBy:"=")[1]
                .replacingOccurrences(of: "+", with: " ")
                .removingPercentEncoding ?? ""
            
            queryStrings[key] = value
        }
        return queryStrings
    }
}
